import 'dart:math';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import '../models/morse_character.dart';

class MorseAudioService {
  static const int sampleRate = 44100;
  static const double frequency = 600.0; // 摩尔斯电码标准频率
  static const int dotDuration = 100; // 点持续时间(ms)
  static const int dashDuration = 300; // 线持续时间(ms)
  static const int elementGap = 100; // 元素间隔(ms)
  static const int characterGap = 300; // 字符间隔(ms)

  bool _isPlaying = false;

  /// 播放单个字符的摩尔斯电码
  Future<void> playCharacter(MorseCharacter character) async {
    if (_isPlaying) return;
    
    _isPlaying = true;
    try {
      for (int i = 0; i < character.elements.length; i++) {
        final element = character.elements[i];
        
        if (element == MorseElement.dot) {
          await _playTone(frequency, dotDuration);
        } else {
          await _playTone(frequency, dashDuration);
        }
        
        // 元素间隔（除了最后一个元素）
        if (i < character.elements.length - 1) {
          await Future.delayed(Duration(milliseconds: elementGap));
        }
      }
    } finally {
      _isPlaying = false;
    }
  }

  /// 播放多个字符的摩尔斯电码序列
  Future<void> playSequence(List<MorseCharacter> characters) async {
    if (_isPlaying) return;
    
    _isPlaying = true;
    try {
      for (int i = 0; i < characters.length; i++) {
        await playCharacter(characters[i]);
        
        // 字符间隔（除了最后一个字符）
        if (i < characters.length - 1) {
          await Future.delayed(Duration(milliseconds: characterGap));
        }
      }
    } finally {
      _isPlaying = false;
    }
  }

  /// 播放指定频率和持续时间的音调
  Future<void> _playTone(double frequency, int durationMs) async {
    try {
      // 生成音频数据
      final samples = _generateTone(frequency, durationMs);
      
      // 使用系统音频播放
      await _playAudioData(samples);
      
      // 等待播放完成
      await Future.delayed(Duration(milliseconds: durationMs));
    } catch (e) {
      // 如果音频播放失败，使用系统声音作为备选
      await _playSystemSound();
      await Future.delayed(Duration(milliseconds: durationMs));
    }
  }

  /// 生成指定频率和持续时间的音调数据
  Uint8List _generateTone(double frequency, int durationMs) {
    final int samples = (sampleRate * durationMs / 1000).round();
    final Float32List audioData = Float32List(samples);
    
    for (int i = 0; i < samples; i++) {
      final double time = i / sampleRate;
      final double sample = sin(2 * pi * frequency * time);
      
      // 添加淡入淡出效果避免爆音
      double envelope = 1.0;
      final double fadeTime = 0.01; // 10ms淡入淡出
      final double fadeSamples = fadeTime * sampleRate;
      
      if (i < fadeSamples) {
        envelope = i / fadeSamples;
      } else if (i > samples - fadeSamples) {
        envelope = (samples - i) / fadeSamples;
      }
      
      audioData[i] = sample * envelope * 0.3; // 降低音量
    }
    
    // 转换为字节数据
    final ByteData byteData = ByteData(audioData.length * 4);
    for (int i = 0; i < audioData.length; i++) {
      byteData.setFloat32(i * 4, audioData[i], Endian.little);
    }
    
    return byteData.buffer.asUint8List();
  }

  /// 播放音频数据（需要音频播放器插件）
  Future<void> _playAudioData(Uint8List audioData) async {
    // 这里可以使用audioplayers包或其他音频播放插件
    // 由于需要添加依赖，这里先用系统声音作为替代
    await _playSystemSound();
  }

  /// 播放系统声音作为备选方案
  Future<void> _playSystemSound() async {
    try {
      await SystemSound.play(SystemSoundType.click);
    } catch (e) {
      // 静默处理错误
    }
  }

  /// 停止播放
  void stop() {
    _isPlaying = false;
  }

  /// 检查是否正在播放
  bool get isPlaying => _isPlaying;
}
